<template>
    <section class="coversation">
		<div class="pic-box" v-show="bigPic.show" @click="showPic('toClose')">
			<img :src="bigPic.src">
		</div>
		<div class="coversationlist">
			<div class="underscore">
				dfjdsjgodf
			</div> 
			<ul>
				<li v-for="item in dataArr">
					<div class="other" :class="{mysay : item.fromAccount == loginInfo.identifier }">
						<img src="http://cangdu.org/files/images/9.jpg" class="head"> 
						<div class="whatsay">
							<div class="whatsay_svg">
								<!--3角小图标-->
							</div> 
							<div class="whatsay_text"> 
								<div v-for="subItem in item.transData" class="say-box">
									<div v-if="subItem.type=='text'">{{subItem.text}}</div>
									<div v-if="subItem.type=='face'" class="face">
										<img :src="subItem.faceUrl">
									</div>
									<div v-if="subItem.type=='img'" class="small-img">
										<img :src="subItem.smallImage" @click.stop="showPic('toShow',subItem.bigImage)">
									</div>
								</div>
							</div>
						</div>
					</div>
				</li>	
			</ul>
		</div>
		<div class="send-box">
			<section v-if="emotions">
				<ul class="face-pack">
					<li v-for="item in emotions" @click="sendFace(item[0])"><img :src="item[1]"></li>
				</ul>
			</section>
			<section class="main-bar">
				<div class="content-box"><input id="inputText" /></div>
				<div class="btn" @click="onSendMsg()">发送</div>
			</section>
		</div>
    </section>
</template>

<script>
import $ from 'jquery';
import Client from "../../config/common";
import convertMsgtoHtml from '../../config/convertMsg';
export default {
    data(){
        return{
			friendId:Client.getQueryString('id'),
			selType:null,//
			loginInfo:{},
			dataArr:null,
			bigPic:{src:'',show:false},//大图
			emotions:null//表情
        }
    },
    created(){
		Client.login((loginInfo) => {
			 this.loginInfo = loginInfo;
			 this.selType = webim.SESSION_TYPE.C2C;
			 this.getLastC2CHistoryMsgs();
		});
		
	},
	mounted(){
		this.emotions = webim.Emotions;
		console.log(webim.Emotions);
    },

    components:{
       
    },

    computed:{

    },

    methods:{
		 //获取最新的c2c历史消息,用于切换好友聊天，重新拉取好友的聊天消息
		getLastC2CHistoryMsgs(cbOk, cbError){
			/*if (selType == webim.SESSION_TYPE.GROUP) {
				alert('当前的聊天类型为群聊天，不能进行拉取好友历史消息操作');
				return;
			}*/
			var lastMsgTime = 0;//第一次拉取好友历史消息时，必须传0
			var msgKey = '';
			var options = {
				'Peer_Account': this.friendId, //好友帐号
				'MaxCnt': 10, //拉取消息条数
				'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
				'MsgKey': msgKey
			};
			webim.getC2CHistoryMsgs(
					options,
					(resp) => {
						var complete = resp.Complete;//是否还有历史消息可以拉取，1-表示没有，0-表示有
						var retMsgCount = resp.MsgCount;//返回的消息条数，小于或等于请求的消息条数，小于的时候，说明没有历史消息可拉取了

						if (resp.MsgList.length == 0) {
							webim.Log.error("没有历史消息了:data=" + JSON.stringify(options));
							return;
						}
						/*getPrePageC2CHistroyMsgInfoMap[selToID] = {//保留服务器返回的最近消息时间和消息Key,用于下次向前拉取历史消息
							'LastMsgTime': resp.LastMsgTime,
							'MsgKey': resp.MsgKey
						};*/

						//数据处理
						//console.log('test',convertMsgtoHtml(resp.MsgList[1]))
						let oldArr = resp.MsgList;
						//let newArr = [];
						oldArr.forEach((arr,index) => {
							let trans = convertMsgtoHtml(arr);
							oldArr[index].transData = trans;
						});
						this.dataArr = oldArr;
						//console.log('this.dataArr',oldArr);
						//设置消息已读
						let selSess = webim.MsgStore.sessByTypeId(this.selType, this.friendId);
						webim.setAutoRead(selSess, true, true);


						if (cbOk)
							cbOk(resp.MsgList);
					},
					cbError
					);
		},
		//发送消息(文本或者表情)
		onSendMsg() {
			let selType = this.selType; //当前聊天类型
			let selToID = this.friendId; //当前选中聊天id（当聊天类型为私聊时，该值为好友帐号，否则为群号）
			let selSess = webim.MsgStore.sessByTypeId(selType, selToID);//获取当前回话
			let friendHeadUrl = '';
			/*if (!selToID) {
				alert("你还没有选中好友或者群组，暂不能聊天");
				$("#send_msg_text").val('');
				return;
			}*/
			//获取消息内容
			let msgtosend = document.querySelector('#inputText').value;
			let msgLen = webim.Tool.getStrBytes(msgtosend);
			
			if (msgtosend.length < 1) {
				alert("发送的消息不能为空!");
				return;
			}
			let maxLen, errInfo;
			if (selType == webim.SESSION_TYPE.C2C) {
				maxLen = webim.MSG_MAX_LENGTH.C2C;
				errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
			} else {
				maxLen = webim.MSG_MAX_LENGTH.GROUP;
				errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
			}
			if (msgLen > maxLen) {
				alert(errInfo);
				return;
			}
			
			if (selSess) {
			let selSess = new webim.Session(selType, selToID, selToID, friendHeadUrl, Math.round(new Date().getTime() / 1000));
			}
			
			var isSend = true;//是否为自己发送
			var seq = -1;//消息序列，-1表示sdk自动生成，用于去重
			var random = Math.round(Math.random() * 4294967296);//消息随机数，用于去重
			var msgTime = Math.round(new Date().getTime() / 1000);//消息时间戳
			var subType;//消息子类型
			if (selType == webim.SESSION_TYPE.C2C) {
				subType = webim.C2C_MSG_SUB_TYPE.COMMON;
			} /*else {
				//webim.GROUP_MSG_SUB_TYPE.COMMON-普通消息,
				//webim.GROUP_MSG_SUB_TYPE.LOVEMSG-点赞消息，优先级最低
				//webim.GROUP_MSG_SUB_TYPE.TIP-提示消息(不支持发送，用于区分群消息子类型)，
				//webim.GROUP_MSG_SUB_TYPE.REDPACKET-红包消息，优先级最高
				subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
			}*/
			//alert('到这63')
			
			var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, this.loginInfo.identifier, subType, this.loginInfo.identifierNick);
			var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
			
			//解析文本和表情
			var expr = /\[[^[\]]{1,3}\]/mg;
			var emotions = msgtosend.match(expr);
			if (!emotions || emotions.length < 1) {
				text_obj = new webim.Msg.Elem.Text(msgtosend);
				msg.addText(text_obj);
			} else {

				for (var i = 0; i < emotions.length; i++) {
					tmsg = msgtosend.substring(0, msgtosend.indexOf(emotions[i]));
					if (tmsg) {
						text_obj = new webim.Msg.Elem.Text(tmsg);
						msg.addText(text_obj);
					}
					emotionIndex = webim.EmotionDataIndexs[emotions[i]];
					emotion = webim.Emotions[emotionIndex];

					if (emotion) {
						face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
						msg.addFace(face_obj);
					} else {
						text_obj = new webim.Msg.Elem.Text(emotions[i]);
						msg.addText(text_obj);
					}
					restMsgIndex = msgtosend.indexOf(emotions[i]) + emotions[i].length;
					msgtosend = msgtosend.substring(restMsgIndex);
				}
				if (msgtosend) {
					text_obj = new webim.Msg.Elem.Text(msgtosend);
					msg.addText(text_obj);
				}
			}

			webim.sendMsg(msg, (resp) => {
				if (selType == webim.SESSION_TYPE.C2C) {//私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
					//addMsg(msg);
				}
				webim.Tool.setCookie("tmpmsg_" + selToID, '', 0);
				console.log('msg',msg);

				//数据解析			
				let addTranslate = convertMsgtoHtml(msg);
				msg.transData = addTranslate;
				console.log('666',msg);

				this.dataArr.push(msg);
				
				document.querySelector('#inputText').value = '';
				//turnoffFaces_box();隐藏表情框
			}, function (err) {
				alert(err.ErrorInfo);
				//$("#send_msg_text").val('');
			});
		},
		showPic(type,src){
			if(type=='toClose'){
				this.bigPic.src = '0';
				this.bigPic.show = false;
			}else{
				this.bigPic.src = src;
				this.bigPic.show = true;
			}
			
		},
		sendFace(text){
			let inputBox = document.querySelector("#inputText");
			inputBox.value += text;
		}
    },
	watch:{
          'loginInfo.onMsgNotify':function(val){  
			  if(val == null){
				  console.log('空对象',)
				  return
			  }else{
				  let listenNew = convertMsgtoHtml(val);
				  val.transData = listenNew;
				  this.dataArr.push(val);
			  }
            }  
	},
}

</script>

<style lang="scss"> 
@import '../../style/public';
.coversation{
	    height:100%;
		background-color: #ebebeb;
		-webkit-overflow-scrolling: touch; 
		.pic-box{
			width:100%;
			height:100%;
			position:fixed;
			z-index:99999;
			background:rgba(0,0,0,.8);
			display:-webkit-box;
			-webkit-box-orient: vertical;
            -webkit-box-align: center;
            -webkit-box-pack: center;
			img{
				max-width:100%;
			}
		}
		.coversationlist{
			position: relative;
			padding:0 .32rem;
			overflow:auto;
			margin:0 auto;
			.underscore{
				padding-top:0.2rem;
				text-align:center;
				//@include sizeColor(0.5546666667rem,#999);
			}
			ul{
				padding-top:.4rem;
				padding-bottom:4.2rem;
				width:100%;
				overflow-scrolling: touch; 
				-webkit-overflow-scrolling: touch; 
				top:0;
				li{
					.other{
						width:100%;
						@include justify(flex-start);
						margin-bottom:0.512rem;
						align-items:top;
						img.head{
							display:block;
							@include widthHeight(1rem,1rem);
						}
						.whatsay{
							position: relative;
							.whatsay_svg{
								@include widthHeight(0.4266666667rem,0.64rem);
								position: absolute;
								top:.5546667rem;
								left:.36rem;
								z-index:2;
								svg{
									display:block;
									@include widthHeight(0.4266666667rem,0.64rem);
								}
							}
							
							.whatsay_text{
								margin-left:.2rem;
								max-width:8.2rem;
								background:#fff;
								padding:0.2rem 0.2rem;
								border:1px solid #d9d9d9;
								border-radius:8px;
								@include sizeColor(0.4rem, #333);
								line-height:0.6rem;
								word-break: break-all;
								.say-box{
									display:inline-block;
									.face{
										width:.6rem;
										img{
											width:100%;
											height:.6rem;
										}
								    }
								}
								
							}
						}
						
					}
					.mysay{
						display:flex;
						flex-direction:row-reverse;
						.whatsay{
							.whatsay_svg{
								right:.36rem;
								left:auto;
							}
							.whatsay_text{
								margin-right:0.2rem;
								margin-left:0;
								background:#9fe658;
							}
						}
					}
				}
			}
			
		}
		.send-box{
			padding:.2rem;
			position:fixed;
			bottom:0;
			left:0;
			background-color: #fff;
			.main-bar{
				display: -webkit-box;
				width:100%;
				height:1.4rem;
				.content-box{
					-webkit-box-flex: 1.0;
					#inputText{
						display:block;
						width:100%;
						height:1rem;
						border:1px solid #ccc;
						padding-left:.2rem;
						border-radius:.1rem;
					}
				}
				.btn{
					width:1.6rem;
					height:1rem;
					vertical-align: middle;
					margin-left:.2rem;
					background:#eaeaea;
					border:1px solid #ccc;
				}
			}
			.face-pack{
				li{
					display: inline-block;
				}
			}
		}
	}
</style>